"""
主应用文件 (app.py)

负责初始化 Flask 应用、配置、数据库连接以及注册路由蓝图。
"""
from flask import Flask
from flask_cors import CORS
import os

from config.config import APP_CONFIG
from routes.meme_routes import meme_bp
from routes.upload_routes import upload_bp
from routes.auth_routes import auth_bp

def create_app():
    """
    创建并配置 Flask 应用实例。

    - 初始化 Flask 应用和 CORS。
    - 加载应用配置。
    - 确保上传目录存在。
    - 初始化数据库连接和存储。 
    - 注册 API 路由蓝图。

    Returns:
        Flask: 配置好的 Flask 应用对象。
    """
    # Initialize Flask app
    app = Flask(__name__)
    CORS(app)  # Enable CORS for all routes to allow cross-origin requests
    
    # Apply configuration from config module
    for key, value in APP_CONFIG.items():
        app.config[key] = value
    
    # Create uploads folder if it doesn't exist to store user uploaded files
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    
    # 确保导入目录存在
    import_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'import')
    os.makedirs(import_dir, exist_ok=True)
    
    # 初始化数据库
    from config.database import init_db, db_session
    from models.db_models import init_default_data
    
    # 初始化数据库表
    init_db()
    
    # 添加示例数据
    session = db_session()
    init_default_data(session)
    session.close()
    
    # 注册应用关闭时清理数据库会话
    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()
    
    # Register blueprints with URL prefixes to organize API routes
    app.register_blueprint(meme_bp, url_prefix='/api')  # Meme-related endpoints
    app.register_blueprint(upload_bp, url_prefix='/api')  # Upload-related endpoints
    app.register_blueprint(auth_bp, url_prefix='/api')   # Authentication endpoints
    
    return app

# Create the application instance
app = create_app()

# Run the application when executed directly
if __name__ == '__main__':
    # debug=True 开启调试模式，方便开发
    # host='0.0.0.0' 允许外部访问
    # port=5000 指定监听端口
    app.run(debug=True, host='0.0.0.0', port=13955) 